package websocket

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

var(
	upgrader = websocket.Upgrader{
		//允许跨域访问
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

//一般模式
func WebSocket(){
	//http://localhost:8888/ws
	http.HandleFunc("/ws", wsHandler)
	http.HandleFunc("/hello", helloHandler)
	//服务端启动
	http.ListenAndServe("0.0.0.0:8888", nil)
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
	//w.Write([]byte("hello"))
	//收到http请求(upgrade),完成websocket协议转换
	//在应答的header中放上upgrade:websoket
	var (
		conn *websocket.Conn
		err error
		//msgType int
		data []byte
	)
	if conn, err = upgrader.Upgrade(w, r, nil); err !=nil {
		//报错了，直接返回底层的websocket链接就会终断掉
		return
	}
	//得到了websocket.Conn长连接的对象，实现数据的收发
	for {
		//Text(json), Binary
		//if _, data, err = conn.ReadMessage(); err != nil {
		if _, data, err = conn.ReadMessage(); err != nil {
			//报错关闭websocket
			goto ERR
		}
		fmt.Printf("data:%T\n",data)
		fmt.Println("data:",string(data))
		//发送数据，判断返回值是否报错
		if err = conn.WriteMessage(websocket.TextMessage, data); err != nil {
			//报错了
			goto ERR
		}
		select {
		case loginuser := <-Ws.LoginLogMsg:
			fmt.Printf("loginuser:",string(loginuser))
			if err = conn.WriteMessage(websocket.TextMessage, loginuser); err != nil {
				//报错了
				goto ERR
			}
		//case c := <-h.u:
		//	if _, ok := h.c[c]; ok {
		//		delete(h.c, c)
		//		close(c.sc)
		//	}
		//case data := <-h.b:
		//	for c := range h.c {
		//		select {
		//		case c.sc <- data:
		//		default:
		//			delete(h.c, c)
		//			close(c.sc)
		//		}
		//	}
		}
	}
	//error的标签
ERR:
	conn.Close()
}

func helloHandler(w http.ResponseWriter, r *http.Request){
	w.Write([]byte("Hello World!"))
}
